<template>
	<div class="upload-image">
		<img :src="imageUrl" v-if="imageUrl">
		<el-row :gutter="20" v-else>
			<el-col :span="11">
				<div class="click-upload" @click="uploadClick">
					<img src="./static/upload.png" v-if="!uploadSrc">
					<img :src="uploadSrc" class="avatar-preview" v-else>
				</div>
			</el-col>
			<el-col :span="11">
				<div class="drag-upload" :class="{'enter-drag':enter}" @drop="drag($event)" @dragenter="dragEnter($event)" @dragover="dragOver($event)" @dragleave="dragLeave($event)" v-if="support">
					<span v-if="!dragSrc">将文件拖到这里上传~</span>
					<img :src="dragSrc" class="avatar-preview" v-else>
				</div>
				<div class="col-md-7 col-md-offset-1 drag-upload" v-else>
					<span>您的浏览器不支持拖拽上传~</span>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="20">
			<div class="upload-bottom">
				<el-button type="primary" v-if="!imageUrl" size="small" :disabled="formData == ''" @click="saveImage">保存</el-button>
				<template v-if="!uploadSrc && !dragSrc && !imageUrl">
					<span>{{msg}}</span>
				</template>
				<template v-else>
					<span @click="clearUpload" class="cursor-pointer">清除</span>
					<span @click="copyImageUrl" v-if="imageUrl" class="cursor-pointer">复制链接</span>
				</template>
	    	</div>
			<input type="file" style="display: none" accept="image/png,image/gif,image/jpeg" ref="imageFile" @change="imageUpload">
		</el-row>
	</div>
</template>

<script>
    import {copyToClipboard} from 'common/dom'

	export default {
		props: {
			url: {
				type: String,
				default: 'uploadImage'
			},
			src: {
				type: String,
				default: ''
			},
			type: {
				type: String,
				default: 'avatar'
			}
		},
		data() {
			return {
				msg: '未选择任何图片',
				formData: '',
				uploadSrc: '',
				dragSrc: '',
				enter: false,
				support: true,
				imageUrl: '',
			}
		},
		created() {
			this.imageUrl = this.src
			let div = document.createElement("div")
			this.support = ('draggable' in div) || ('ondrapstart' in div && 'ondrop' in div)
		},
		methods: {
			uploadClick() {
				this.$refs.imageFile.click()
			},
			clearUpload() {
				this.uploadSrc = ''
				this.dragSrc = ''
				this.$refs.imageFile.value = ''
				this.formData = ''
				this.imageUrl = ''
			},
			drag(e) {
				e.stopPropagation()
    			e.preventDefault()
    			this.enter = false
    			if (!e.dataTransfer.files[0].size){
					return false	
				}
    			this.readerImage(e.dataTransfer.files[0], 2)
			},
			dragEnter(e) {
				e.stopPropagation()
    			e.preventDefault()
    			this.enter = true
			},
			dragLeave(e) {
				e.stopPropagation()
    			e.preventDefault()
    			this.enter = false
			},
			dragOver(e) {
				e.stopPropagation()
    			e.preventDefault()
    			return false
			},
			imageUpload(e) {
				if (!e.target.files[0].size){
					return false	
				}
				this.readerImage(e.target.files[0], 1)
			},
			readerImage(file,type) {
				//控制上传文件的类型				
				let fileType = file.type
				if(fileType.indexOf('image') === -1) {
					this.$message('只能上传图片哦~')
					return false
				}

				//控制上传图片的大小
				let size = file.size
				if(size / 1024 / 1024 > 2) {
					this.$message('图像上传不能大于2M~')
					return false
				}

				//清除已记录的图片数据
				this.clearUpload()
				//读取文件内容并显示预览效果
				let reader = new FileReader()
				let _this= this
     			reader.readAsDataURL(file)
     			reader.onload = function () {  
			       	if(type == 1) {
			       		_this.uploadSrc = this.result
			       	}else{
			       		_this.dragSrc = this.result
			       	}
		     	}
		     	//将文件记录于vue对象中
		     	let formData = new FormData()
				formData.append('file', file)
				formData.append('type', this.type)
				this.formData = formData
			},
			saveImage() {
				if(this.formData == '') {
					this.$message('必须选择一个文件才能保存~')
					return false
				}
				if(!this.formData.get('file')) {
					this.$message('必须选择一个文件才能保存~')
					return false
				}
				let config = {
		        	headers: {'Content-Type':'multipart/form-data'}
		        }
		        this.$http.post(this.url, this.formData, config).then((response)=>{
		        	this.clearUpload()
		        	this.imageUrl = response.data
		        	this.$emit('uploadSuccess', this.imageUrl)
		        	this.$message('上传成功')
		        }).catch((error)=> {
		        	this.$message('上传失败')
		        })
			},
			copyImageUrl() {
				if(copyToClipboard(this.imageUrl)) {
					this.$notify({
			          title: '复制成功',
			          message: '图片链接已复制到剪贴板',
			          type: 'success'
			        })
				} else {
					this.$notify({
			          title: '复制失败',
			          message: '您的浏览器不支持剪贴',
			          type: 'warning'
			        })
				}
			}
		},
		watch: {
			src(curVal, oldVal) {
				this.imageUrl = curVal
			}
		}
	}
</script>

<style scope>
	.upload-image>img {
		max-width: 100%;
		max-height: 180px;
		margin-left: 10px;
		margin-top: 10px;
	}

	.upload-image {
		border: 1px dashed #f6f6f6;
		margin-top: 10px;
		max-width: 98%;
	}
	.upload-image img{
		vertical-align: middle;
	}
	.upload-image .cursor-pointer {
		cursor: pointer !important;
	}
	.upload-image .cursor-pointer:hover {
		color: #ffe153;
	}
	.upload-image .avatar-box {
		margin-top: 20px;
		margin-bottom: 20px;
		border-radius: 4px;
		border: 1px solid #f6f6f6;
	}
	.upload-image .click-upload {
		vertical-align: middle;
		cursor: pointer;
	}

	.upload-image .click-upload,.drag-upload{
		text-align: center;
		margin-top: 10px;
		margin-bottom: 10px;
		border-radius: 4px;
		border: 1px solid #f6f6f6;
		height: 150px;
		line-height: 150px;
		color: #adadad;
	}

	.upload-image .avatar-preview {
		display: inline-block;
		max-width: 130px;
		max-height: 130px;
	}

	.upload-image .upload-bottom {
		padding-left: 10px;
	    margin: 8px 0;
	    line-height: 25px;
	    font-size: 14px;
	}

	.upload-image .upload-bottom>span{
		margin-left: 10px;
		color: #adadad;
		cursor: default;
	}

	.upload-image .enter-drag {
		border: 1px solid #ffe153;
	}
</style>